#include "roleconfigdialog.h"
#include "qsqlquery.h"
#include "ui_roleconfigdialog.h"

#include <QDebug>
#include "mainwindow.h"

RoleConfigDialog::RoleConfigDialog(QWidget *parent, int id) :
    QDialog(parent),
    ui(new Ui::RoleConfigDialog)
{
    ui->setupUi(this);
    setWindowModality(Qt::ApplicationModal);
    item_parent = (RoleMgmt *) parent;

    if(id <= 0){
        setWindowTitle("新增角色");
        ui->cmb_type->setCurrentIndex(-1);
        ui->cmb_status->setCurrentIndex(-1);
    }else{
        setWindowTitle("编辑角色");
        QSqlQuery query = mydb->query("dm_role", "name,type,description,enabled,sort",QString(" WHERE id='%1'").arg(id));
        if(query.next()){
            ui->le_name->setText(query.value(0).toString());
            ui->cmb_type->setCurrentIndex(ui->cmb_type->findText(query.value(1).toString()));
            ui->le_remark->setText(query.value(2).toString());
            ui->cmb_status->setCurrentIndex(query.value(3).toInt());
            ui->le_pos->setText(query.value(4).toString());

            setWindowTitle("编辑角色 - " + ui->le_name->text());
            item_id = id;
        }
    }
}

RoleConfigDialog::~RoleConfigDialog()
{
    delete ui;
}

void RoleConfigDialog::on_btn_save_clicked()
{
    QString sql;
    QSqlQuery query;

    QString name = ui->le_name->text();
    QString remark = ui->le_remark->text();
    QString pos = ui->le_pos->text();
    QString type = ui->cmb_type->currentText();
    int status = ui->cmb_status->currentIndex();

    if(item_id == -1){
        sql = QString("INSERT INTO dm_role (name, type, description, enabled, sort, delete_flag) \
values('%1', '%2', '%3', '%4', '%5', '%6');").arg(name).arg(type).arg(remark).arg(status).arg(pos).arg(0);
        if(query.exec(sql)){
            mydb->addLog(DM_Window->current_user_id, "角色管理", QString("新增角色<%1>").arg(name), "1");
        }
    }else{
        sql = QString("UPDATE dm_role SET name='%1', type='%2', description='%3', enabled='%4', sort='%5' \
WHERE id='%6';").arg(name).arg(type).arg(remark).arg(status).arg(pos).arg(item_id);
        if(query.exec(sql)){
            mydb->addLog(DM_Window->current_user_id, "角色管理", QString("更改角色<%1>").arg(name), "1");
        }
    }
    qDebug() << sql;
//    query.exec(sql);

    item_parent->updatePage();
    this->close();
}

void RoleConfigDialog::on_btn_cancel_clicked()
{
    this->close();
}

